package com.example.distinguishcolors;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.example.distinguishcolors.adapter.ColorAdapter;
import com.example.distinguishcolors.domain.GameColor;
import com.example.distinguishcolors.utils.ColorUtils;
import com.example.distinguishcolors.view.LyyDialog;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.PrimitiveIterator;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private RecyclerView rv;
    private Button restartBtn;
    private Button pauseBtn;
    public Toolbar toolbar;
    private TextView timeTv;
    private TextView totalTimeTv;
    private List<GameColor> list=new ArrayList<>();
    private ColorAdapter colorAdapter;
    public static final int NEXT=1;
    public static final int SPEND_TIME=2;
    public static final int SELECT_TIME=10;//选择颜色的时间
    public GameHandler gameHandler;
    private boolean isPause=false;//标志游戏是否暂停
    private boolean isFirstTime=true;//是否是打开游戏后的第一次玩
    private long spendT;//游戏进行了多长时间，单位：毫秒
    private static final String TAG = "MainActivity";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initData();
        initView();

    }

    private void initData() {
        gameHandler=new GameHandler(this);
        list.addAll(ColorUtils.getRandomColors(100));
    }

    private void initView() {
        rv=findViewById(R.id.rv);
        rv.setLayoutManager(new GridLayoutManager(this,4));
        colorAdapter=new ColorAdapter(list,this);
        rv.setAdapter(colorAdapter);
        colorAdapter.notifyDataSetChanged();
        restartBtn=findViewById(R.id.restartBtn);
        restartBtn.setOnClickListener(this);
        pauseBtn=findViewById(R.id.pauseBtn);
        pauseBtn.setEnabled(false);
        pauseBtn.setOnClickListener(this);
        toolbar=findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        timeTv=findViewById(R.id.timeTv);
        totalTimeTv=findViewById(R.id.totalTimeTv);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.restartBtn:
                if(isFirstTime){
                    restartBtn.setText("重新开始");
                    isFirstTime=false;
                }
                list.clear();
                list.addAll(ColorUtils.getRandomColors(100));
                colorAdapter.notifyDataSetChanged();
                gameHandler.removeMessages(NEXT);
                gameHandler.setCount(SELECT_TIME);//重置时间
                gameHandler.sendEmptyMessage(NEXT);
                gameHandler.removeMessages(SPEND_TIME);//先移除旧的消息
                gameHandler.sendEmptyMessage(SPEND_TIME);
                spendT=0;//把总耗时重置为0
                colorAdapter.setGameOver(false);//标志游戏未结束
                colorAdapter.setDis(ColorAdapter.COLOR_DIS);//重置颜色差值
                colorAdapter.setLevelNum(1);//把关卡重置为1
                toolbar.setSubtitle("第1关");
                pauseBtn.setEnabled(true);
                break;
            case R.id.pauseBtn:
                if(!isPause){
                    gameHandler.removeMessages(NEXT);
                    pauseBtn.setText("继续游戏");
                    isPause=!isPause;
                }else {
                    gameHandler.sendEmptyMessage(NEXT);
                    pauseBtn.setText("暂停游戏");
                    isPause=!isPause;
                }

                break;
            default:
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.game_menu,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int itemId = item.getItemId();
        if(itemId==R.id.exit){
            LyyDialog lyyDialog=new LyyDialog(MainActivity.this,new LyyDialog.SelectCallBack(){
                @Override
                public void onPositiveClick() {
                    System.exit(0);
                }

                @Override
                public void onNegativeClick() {
                    dismiss();
                }
            },true);
            lyyDialog.setContent("您确定要退出游戏吗？");
            lyyDialog.show();
        }else if(itemId==R.id.leaderboard){
            startActivity(new Intent(MainActivity.this,LeaderboardActivity.class));
        }
        return super.onOptionsItemSelected(item);
    }

    public long getSpendT() {
        return spendT;
    }

    public boolean isFirstTime() {
        return isFirstTime;
    }

    public boolean isPause() {
        return isPause;
    }

    public Button getPauseBtn() {
        return pauseBtn;
    }

    public TextView getTimeTv() {
        return timeTv;
    }

    public GameHandler getGameHandler() {
        return gameHandler;
    }

    public static class GameHandler extends Handler{
        private int count=SELECT_TIME;//倒计时
        private final WeakReference<MainActivity> weakReference;

        public GameHandler(MainActivity activity) {
            this.weakReference =new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            MainActivity activity = weakReference.get();
            switch (msg.what){
                case NEXT:
                    if(activity.timeTv!=null){
                        activity.timeTv.setText("本关还剩："+count+"s");
                    }
                    count--;
                    if(count>=0){
                        sendEmptyMessageDelayed(NEXT,1000);
                    }else {//超时，游戏结束
                        activity.colorAdapter.setGameOver(true);
                        removeMessages(SPEND_TIME);
                        LyyDialog lyyDialog=new LyyDialog(activity, new LyyDialog.SelectCallBack() {
                            @Override
                            public void onPositiveClick() {
                                ArrayList<GameColor> gameColors=new ArrayList<>();
                                gameColors.addAll(activity.list);
                                activity.list.clear();
                                activity.colorAdapter.notifyDataSetChanged();
                                activity.list.addAll(gameColors);
                                activity.colorAdapter.notifyDataSetChanged();
                            }
                        });
                        lyyDialog.setContent("您已超时，游戏结束！");
                        activity.getTimeTv().setText("游戏已结束...");
                        activity.pauseBtn.setEnabled(false);
                        lyyDialog.show();
                    }
                    break;
                case SPEND_TIME:
                    int min= (int) (activity.spendT/(1000*60));//分钟
                    int second= (int) (activity.spendT-(min*60*1000))/1000;//秒
                    activity.totalTimeTv.setText("总耗时："+min+"分"+second+"秒");
                    sendEmptyMessageDelayed(SPEND_TIME,1000);
                    long spe = activity.spendT;
                    spe+=1000;
                    activity.spendT=spe;
                    break;
                default:
            }
        }

        public int getCount() {
            return count;
        }

        public void setCount(int count) {
            this.count = count;
        }
    }
}